import logging
import time
from datetime import datetime

from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from django.forms.models import model_to_dict
from django.core import serializers

# Create your views here.
from django.views import View

from active.models import Active
from comment.comviews import com_views, server_time
from comment.log_code import LogCodes
from user.models import User
from .models import PWNote
import json


class PnoteView(View):
    def render(self, message, code, data=None):
        ret = {}
        ret["message"] = message
        ret["err_code"] = code
        ret["data"] = data
        return JsonResponse(ret)
    
    def get(self, request):
        """
        根据用户id获得密码本列表
        :param request:
        :return:
        """
        ret = {}
        id = request.GET.get("id")
        if id is None:
            message = "id is null"
            err_code = LogCodes.SELECT_ERROR
        else:
            pwnote = PWNote.objects.filter(user=id)
            if pwnote != None:
                message = "success"
                err_code = LogCodes.SELECT_OK
                ret["data"] = [model_to_dict(value) for value in
                               pwnote]  # serializers.serialize("json", pwnote) if pwnote.count()>0 else None
            else:
                message = "params is error"
                err_code = LogCodes.SELECT_ERROR
        ret["message"] = message
        ret["err_code"] = err_code
        return JsonResponse(ret, safe=False)
    
    def post(self, request):
        ret = {}
        body = json.loads(request.body)
        user = body.get("user")
        pwdata = body.get("pwdata")
        pwuser = body.get("pwuser")
        remarks = body.get("remarks")
        
        if not all([id, user, pwdata, remarks]):
            return self.render("params is not full", LogCodes.SELECT_ERROR)
        user = User.objects.get(id=user)
        if user == None:
            return self.render("params is not full", LogCodes.SELECT_ERROR)
        rows = PWNote.objects.create(user=user, pwdata=pwdata, remarks=remarks, pwuser=pwuser)
        if rows != 0:
            Active.objects.create(user=user, pwnote=rows, commands=0, post_time=datetime.now())
            message = "success"
            code = LogCodes.UPDATE_OK
            ret["data"] = {"id": rows.id}
        else:
            message = "update is error"
            code = LogCodes.UPDATE_ERROR
        
        ret["message"] = message
        ret["err_code"] = code
        return JsonResponse(ret, safe=False)
    
    def put(self, request):
        ret = {}
        body = json.loads(request.body)
        id = body.get("id")
        user = body.get("user")
        pwdata = body.get("pwdata")
        pwuser = body.get("pwuser")
        remarks = body.get("remarks")
        
        if not all([id, user, pwdata, remarks]):
            return self.render("params is not full", LogCodes.SELECT_ERROR)
        user = User.objects.get(id=user)
        if user == None:
            return self.render("params is not full", LogCodes.SELECT_ERROR)
        rows = PWNote.objects.filter(id=id).update(user=user, pwdata=pwdata, remarks=remarks, pwuser=pwuser)
        if rows != 0:
            pwnote = PWNote.objects.get(id=id)
            Active.objects.create(user=user, pwnote=pwnote, commands=2, post_time=datetime.now())
            message = "success"
            code = LogCodes.UPDATE_OK
            ret["data"] = {"id": id}
        else:
            message = "update is error"
            code = LogCodes.UPDATE_ERROR
        
        ret["message"] = message
        ret["err_code"] = code
        return JsonResponse(ret)
    
    def delete(self, request):
        ret = {}
        body = json.loads(request.body)
        id = body.get("id")
        user = body.get("user")
        
        if not all([id, user]):
            return self.render("params is not full", LogCodes.SELECT_ERROR)
        
        user = User.objects.get(id=user)
        if user == None:
            return self.render("params is not full", LogCodes.SELECT_ERROR)
        pwnote = PWNote.objects.get(id=id)
        if pwnote == None:
            return self.render("params is not full", LogCodes.SELECT_ERROR)
        active = Active.objects.create(user=user, pwnote=pwnote, commands=1, post_time=datetime.now())
        rows = PWNote.objects.filter(id=id).filter(user=user).delete()
        if rows != 0:
            message = "success"
            code = LogCodes.DELETE_OK
            ret["data"] = {"id": id}
        else:
            active.delete()
            message = "delete is error"
            code = LogCodes.DELETE_ERROR
        
        ret["message"] = message
        ret["err_code"] = code
        return JsonResponse(ret)


def pwnote_list(params):
    """
    根据用户id获得密码本列表
    :param request:
    :return:
    """
    data = None
    user_id = params.get("user_id")
    if user_id is None:
        message = "id is null"
        err_code = LogCodes.SELECT_ERROR
        success = 0
    else:
        actives = Active.objects.filter(Q(user_id=user_id) | Q(pwnote_id__is_delete=False))
        # pwnote = active.values("active")
        if actives.count() != 0:
            success = 1
            message = "success"
            err_code = LogCodes.SELECT_OK
            active_list = list(actives)
            for active in active_list:
                active["pwnote"] = model_to_dict(PWNote.objects.get(id=active.pwnote_id))
            data = active_list
        else:
            success = 0
            message = "params is error"
            err_code = LogCodes.SELECT_ERROR
    return [err_code, message, data, success, server_time()]


def pwnote_create(params):
    """
    创建密码数据
    :param params:
    :return:
    """
    data = None
    user_id = params.get("user_id")
    pwdata = params.get("pwdata")
    pwuser = params.get("pwuser")
    remarks = params.get("remarks")
    platform = params.get("platform")
    body_id = params.get("body_id")
    
    if not all([id, user_id, pwdata, platform]):
        return [LogCodes.SELECT_ERROR, "params is not full", None, 0, server_time()]
    try:
        user = User.objects.get(uid=user_id)
    except Exception as e:
        logging.error(e)
        return [LogCodes.SELECT_ERROR, "uid is empty", None, 0, server_time()]
    if user is None:
        return [LogCodes.SELECT_ERROR, "uid is empty", None, 0, server_time()]
    try:
        rows = PWNote.objects.create(pwdata=pwdata, remarks=remarks, pwuser=pwuser, platform=platform)
    except Exception as e:
        logging.error(e)
        return [LogCodes.CREATE_ERROR, "cretae active is error", 0, server_time()]
    if rows != 0:
        active = Active.objects.create(body_id=body_id, user_id=user, pwnote_id=rows, commands=0)
        message = "success"
        code = LogCodes.UPDATE_OK
        data = {"body_id": active.body_id}
        success = 1
    else:
        message = "update is error"
        code = LogCodes.UPDATE_ERROR
        success = 0
    
    return [code, message, data, success, server_time()]


def pwnote_update(params):
    data = None
    body_id = params.get("body_id")
    user_id = params.get("user_id")
    update_time = params.get("update_time")
    pwdata = params.get("pwdata")
    pwuser = params.get("pwuser")
    remarks = params.get("remarks")
    platform = params.get("platform")
    
    if not all([body_id, user_id, pwdata, platform, update_time]):
        return ["params is not full", LogCodes.SELECT_ERROR, None, 0, server_time()]
    try:
        user = User.objects.get(id=user_id)
    except Exception as e:
        logging.error(e)
        return ["params is not full", LogCodes.SELECT_ERROR, None, 0, server_time()]
    if user is None:
        return ["params is not full", LogCodes.SELECT_ERROR, None, 0, server_time()]
    rows = PWNote.objects.filter(id=id).update(user=user, pwdata=pwdata, remarks=remarks, pwuser=pwuser,
                                               platform=platform)
    if rows != 0:
        pwnote = PWNote.objects.get(id=id)
        Active.objects.create(user=user, pwnote=pwnote, commands=2, post_time=datetime.now())
        message = "success"
        code = LogCodes.UPDATE_OK
        success = 1
        data = {"id": id}
    else:
        success = 0
        message = "update is error"
        code = LogCodes.UPDATE_ERROR
    
    return [code, message, data, success, server_time()]


def pwnote_delete(params):
    data = None
    id = params.get("id")
    user = params.get("user")
    
    if not all([id, user]):
        return [LogCodes.SELECT_ERROR, "params is not full", None, 0, server_time()]
    
    user = User.objects.get(id=user)
    if user == None:
        return [LogCodes.SELECT_ERROR, "params is not full", None, 0, server_time()]
    try:
        pwnote = PWNote.objects.get(id=id)
    except Exception as e:
        return ["params is not full", LogCodes.SELECT_ERROR, None, 0, server_time()]
    if pwnote == None:
        return ["params is not full", LogCodes.SELECT_ERROR, None, 0, server_time()]
    active = Active.objects.create(user=user, pwnote=pwnote, commands=1, post_time=datetime.now())
    rows = PWNote.objects.filter(id=id).filter(user=user).delete()
    if rows != 0:
        message = "success"
        code = LogCodes.DELETE_OK
        success = 1
        data = {"id": id}
    else:
        active.delete()
        message = "delete is error"
        code = LogCodes.DELETE_ERROR
        success = 0
    return [code, message, data, success, server_time()]


def pwnote_info(params):
    ret = {}
    id = params.get("id")
    if id is None:
        message = "id is null"
        err_code = LogCodes.SELECT_ERROR
    else:
        try:
            active = Active.objects.get(body_id=id)
        except Exception as e:
            logging.error(e)
            return ["params is not full", LogCodes.SELECT_ERROR, None, 0, server_time()]
        if active != None:
            pwnote = active.pwnote_id
            message = "success"
            err_code = LogCodes.SELECT_OK
            ret["data"] = model_to_dict(pwnote)
        else:
            message = "params is error"
            err_code = LogCodes.SELECT_ERROR
    ret["message"] = message
    ret["err_code"] = err_code
    return JsonResponse(ret, safe=False)


def index(request):
    return com_views(request, {
        "list": pwnote_list,
        "update": pwnote_update,
        "create": pwnote_create,
        "delete": pwnote_delete,
        "info": pwnote_info,
    })
